package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Wxt
 * @create 2022-02-08 10:13
 */
public class JdbcUtils {
    private static DataSource source;
    private static ThreadLocal<Connection> conns = new ThreadLocal<>();
    static {
        Properties properties = new Properties();
        InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(is);
            source = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection()  {
        Connection conn = conns.get();
        try {
            if(conn == null) {
                conn = source.getConnection();
                conns.set(conn);
                conn.setAutoCommit(false);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    /**
     * 提交事务，并关闭释放连接
     */
    public static void commitAndClose() {
        Connection conn = conns.get();
        try {
            if(conn != null) {
                conn.commit();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DbUtils.closeQuietly(conn);
        }
        conns.remove();
    }

    /**
     * 回滚事务，并关闭连接
     */
    public static void rollBackAndClose() {
        Connection conn = conns.get();
        try {
            if(conn != null) {
                conn.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DbUtils.closeQuietly(conn);
        }
        conns.remove();
    }
}
